package com.zry.yard.ui.activity.map

import android.util.Log
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.search.geocode.*

class MapAddressUtil(locationBean: LocationBean, versionInt: Int) : OnGetGeoCoderResultListener {

    private var mSearch: GeoCoder? = null
    private var location: LocationBean? = null

//    versionInt=1:表示根据经纬度查找地址
//    versionInt=0：表示根据地址查找经纬度

    init {
        // 初始化搜索模块，注册事件监听
        mSearch = GeoCoder.newInstance()
        mSearch?.setOnGetGeoCodeResultListener(this)

        val ptCenter = LatLng(locationBean.latitude, locationBean.longitude)
        mSearch?.reverseGeoCode(ReverseGeoCodeOption().location(ptCenter).newVersion(versionInt))
    }


    override fun onGetGeoCodeResult(geoCodeResult: GeoCodeResult?) {
        val strInfo = String.format("纬度：%f 经度：%f",
                geoCodeResult!!.location.latitude, geoCodeResult.location.longitude)
        location = LocationBean(geoCodeResult.location.latitude, geoCodeResult.location.longitude)
        if (listener != null) {
            listener?.handleResultLocation(location!!)
        }
    }

    override fun onGetReverseGeoCodeResult(reverseGeoCodeResult: ReverseGeoCodeResult?) {
        val locationAddress = reverseGeoCodeResult?.address
        val locationCode = reverseGeoCodeResult?.adcode
        Log.e("locationCode", reverseGeoCodeResult!!.addressDetail.countryCode.toString())
        Log.e("locationCode", reverseGeoCodeResult.addressDetail.adcode.toString())

        if (listener != null) {
            listener?.handleResultAddress(locationAddress!!)
        }
    }


    private var listener: AddressListener? = null

    interface AddressListener {
        fun handleResultLocation(location: LocationBean)
        fun handleResultAddress(locationAddress: String)

    }

    fun setListener(listener: AddressListener): MapAddressUtil {
        this.listener = listener
        return this
    }
}